package com.example.login

import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.example.common.view.view.BaseMvvmActivity
import com.example.login.databinding.ActivityRegisterBinding
import com.example.login.vm.RegisterViewModel
import com.tencent.mmkv.MMKV
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.random.Random

@AndroidEntryPoint
@Route(path = "/login/RegisterActivity")
class RegisterActivity : BaseMvvmActivity<ActivityRegisterBinding>() {
    override fun getLayoutId(): Int =R.layout.activity_register
    val registerViewModel:RegisterViewModel by viewModels()
    override fun initView() {
        super.initView()
        mDataBinding.btnCode.setOnClickListener {
            val random = Random.nextInt(899999)+100000
            ToastUtils.showLong("验证码: "+random)
            MMKV.defaultMMKV().encode("btnCode",random)
            mDataBinding.btnCode.isEnabled=false
            lifecycleScope.launch {
                for (i in 30 downTo 0){
                    delay(1000)
                    mDataBinding.btnCode.text="$i 秒再次获取"
                }
                mDataBinding.btnCode.text="获取验证码"
                mDataBinding.btnCode.isEnabled=true
            }
        }
        mDataBinding.btnRegister.setOnClickListener {
            if (mDataBinding.phone.text.length!=11){
                ToastUtils.showLong("手机号码不正确")
            }else if (mDataBinding.password.text.length==0){
                ToastUtils.showLong("密码不能为空")
            }else if (mDataBinding.edCode.text.length==0){
                ToastUtils.showLong("验证码不能为空")
            }else if (!mDataBinding.password.text.toString().equals(mDataBinding.repassword.text.toString())){
                ToastUtils.showLong("两次密码不一致")
            }else{
                registerViewModel.postRegister(mDataBinding.password.text.toString(),mDataBinding.phone.text.toString())
            }
        }
        registerViewModel.mSuccessLiveData.observe(this){
            ToastUtils.showLong("注册成功")
            finish()
        }
        registerViewModel.mErrorLiveData.observe(this){
            ToastUtils.showLong(it)
        }
    }
}